package com.heima.comment.service.impl;

import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustomException;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.utils.threadlocal.AppThreadLocalUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceimpl implements CommentRepayService {

    @Resource
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        //参数校验
        if (dto == null || dto.getCommentId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        if (dto.getSize() == null || dto.getSize() < 0) {
            dto.setSize(10);
        }

        if (dto.getMinDate() == null) {
            dto.setMinDate(new Date());
        }

        //查询所有回复
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime")
                .lt(dto.getMinDate())).with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(dto.getSize()), ApCommentRepay.class);

        //根据点赞数量排序
        List<ApCommentRepay> commentRepays = apCommentRepays.stream().sorted(Comparator.comparing(ApCommentRepay::getLikes).reversed()).collect(Collectors.toList());

        //获取当前登录用户
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(commentRepays);
        }

        //查询用户点赞的评论
        List<ApCommentRepayLike> commentRepayLikes = mongoTemplate.find(Query.query(Criteria.where("authorId").is(user.getId())), ApCommentRepayLike.class);
        //创建添加用户点赞信息的集合
        ArrayList<ApCommentRepay> apCommentVoList = new ArrayList<>();


        for (ApCommentRepay commentRepay : commentRepays) {

            ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
            BeanUtils.copyProperties(commentRepay, apCommentRepayVo);

            for (ApCommentRepayLike commentRepayLike : commentRepayLikes) {
                if (apCommentRepayVo.getId().equals(commentRepayLike.getCommentRepayId())) {
                    apCommentRepayVo.setOperation((short) 0);
                }

            }
            apCommentVoList.add(apCommentRepayVo);
        }

        return ResponseResult.okResult(apCommentVoList);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        //参数校验
        if (dto.getCommentId() == null || StringUtils.isBlank(dto.getContent())) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //判断用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //查询回复的评论是否存在
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //封装添加数据
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(user.getId());
        apCommentRepay.setAuthorName(user.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        //添加
        mongoTemplate.insert(apCommentRepay);

        //回复数量加1
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {
        //参数校验
        if (dto.getCommentRepayId() == null || dto.getOperation() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        if (dto.getOperation().intValue() != 0 && dto.getOperation().intValue() != 1) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            throw new CustomException(AppHttpCodeEnum.NEED_LOGIN);
        }

        //判断回复的数据是否存在
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay == null) {
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //开始添加
        if (dto.getOperation().intValue() == 0) {
            apCommentRepay.setLikes(apCommentRepay.getLikes() + 1);
            mongoTemplate.save(apCommentRepay);
            //封装添加数据
            ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
            apCommentRepayLike.setAuthorId(user.getId());
            apCommentRepayLike.setCommentRepayId(apCommentRepay.getId());
            apCommentRepayLike.setOperation(dto.getOperation());
            //添加
            mongoTemplate.save(apCommentRepayLike);
        } else {  //取消

            apCommentRepay.setLikes(apCommentRepay.getLikes() - 1 < 0 ? 0 : (apCommentRepay.getLikes() - 1));
            mongoTemplate.save(apCommentRepay);

            mongoTemplate.remove(Query.query(Criteria.where("commentRepayId").is(dto.getCommentRepayId()).and("authorId").is(user.getId())),ApCommentRepayLike.class);
        }

        //数据返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes", apCommentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
